/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.enterprise.web;

import com.assg2.dao.DaoViewer;
import com.movie.Viewer;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Kevin
 */
public class SearchFriendCommand implements Command {

    public SearchFriendCommand() {
    }

    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //TODO: set the response content type to "text/html" here
        //TODO: You'll have to use getWriter() to output some HTML texts
        //TODO: close the output stream

        response.setContentType("text/html");// from response, set content type
        PrintWriter out = response.getWriter();// from response, get output writer     
        HttpSession session = request.getSession(true);
        Viewer user = (Viewer) session.getAttribute("user");

        String name = request.getParameter("friendname");
        List<Viewer> resultList = new ArrayList<Viewer>();
        DaoViewer dv = new DaoViewer();
        List viewerList = dv.listall();
        if (viewerList != null) {
            for (int i = 0; i < viewerList.size(); i++) {
                Viewer v = (Viewer) viewerList.get(i);
                if (v != null && v.getFirstname() != null && v.getLastname() != null) {
                    if (!v.getIdviewer().equals(user.getIdviewer())) {
                        if (v.getFirstname().contains(name) || v.getLastname().contains(name)) {
                            resultList.add(v);
                        }
                    }
                }
//                request.setAttribute("message", "Problem here");
//                return "message";
            }
            if (resultList.size() != 0) {
                request.setAttribute("resultList", resultList);
                return ("/friendSearchResult.jsp");
            }

        }
        if (resultList.size() == 0) {
            request.setAttribute("message", "No result found, you may want to <a href='searchFriend.jsp'>search again</a>");
            return "message";

        } else {
            return null;
        }
    }
}
